import axios from "axios";
import qs from "qs";
import md5 from 'js-md5';
import {
    Notification
} from "element-ui";
import store from "@/store";
import router from '@/router';
import baseURL from './baseURL';

const salt = '4028818e4f2a27d4014f2b0855570012';

const service = axios.create({
    baseURL: baseURL.url,
    // timeout: 60000, //响应时长可根据业务需求自行设置
    responseType: "json",
    withCredentials: false,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        'signature': '',
    }
})

//请求拦截器
service.interceptors.request.use(config => {
    let METHOD = config.method.toUpperCase();
    if (METHOD === "POST" || METHOD === "PUT" || METHOD === "DELETE") {
        if (!config.contentType) { // 若没有自定义contentType则用默认的
            // if (config.hasOwnProperty('tenementId') && config.tenementId) {
            //     config.data = {
            //         token: store.state.token.token,
            //         tenementId: config.tenementId,
            //         cur_sys_id: store.state.token.systemId,
            //         ...config.data,
            //     }
            // } else if (config.hasOwnProperty('tenementId') && config.tenementId == '') {
            //     config.data = {
            //         token: store.state.token.token,
            //         cur_sys_id: store.state.token.systemId,
            //         ...config.data,
            //     }
            // } else {
            //     config.data = {
            //         token: store.state.token.token,
            //         tenementId: store.state.token.tenementId,
            //         cur_sys_id: store.state.token.systemId,
            //         ...config.data,
            //     }
            // }
            config.data = {
                token: store.state.token.token,
                tenementId: store.state.token.tenementId,
                // cur_sys_id: store.state.token.systemId,
                shopId: store.state.token.sceneId,
                sellId: store.state.token.sellerId,
                ...config.data,
            }

            config.headers['signature'] = md5(objKeySort(config.data) + salt, 32).toUpperCase();

            config.data = qs.stringify(config.data);
        }
    } else if (METHOD == 'GET') { // 判断get参数拼接方式 加入tenementId
        if (config.url.indexOf('?') < 0) {
            if (config.url.indexOf('tenementId') < 0) {
                config.url += '?token=' + store.state.token.token + '&tenementId=' + store.state.token.tenementId;
            } else {
                config.url += '?token=' + store.state.token.token;
            }
        } else {
            if (config.url.indexOf('token') < 0) {
                config.url += '&token=' + store.state.token.token;
            }
            if (config.url.indexOf('tenementId') < 0) {
                config.url += '&tenementId=' + store.state.token.tenementId;
            }
        }
        config.url += '&cur_sys_id=' + store.state.token.systemId;
    }
    if (store.state.token.token) {
        config.headers['token'] = store.state.token.token;
    }
    if (config.contentType) { // 设置自定义contentType
        config.headers['Content-Type'] = config.contentType;
    }
    return config
}, error => {
    return Promise.reject(error)
});

//响应拦截器
service.interceptors.response.use(response => {
    /** 以下可根据返回的code值来做用户权限操作*/
    if (response.data.code == 1000) {

    } else if (response.data.code == 9003) {
        // router.replace({ path: '/login' });
    } else if (response.data.code == 9999) {
        Notification({
            title: '提示',
            type: 'error',
            message: '系统错误，请重试或联系管理员！'
        })
    } else {
        Notification({
            title: '提示',
            type: 'error',
            message: response.data.msg
        })
    }
    return response
}, error => {
    Notification({
        title: '提示',
        type: 'error',
        message: '请求错误'
    })
    return Promise.reject(error)
})

const objKeySort = (obj) => { // ASCII码排序的函数
    var newkey = Object.keys(obj).sort();
    // 先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    let str = '';
    for (var i = 0; i < newkey.length; i++) { // 遍历newkey数组
        if (obj[newkey[i]] || obj[newkey[i]] === 0) {
            if (typeof obj[newkey[i]] == "object") {
                obj[newkey[i]] = JSON.stringify(obj[newkey[i]])
            }
            str += ((str.indexOf("=") != -1) ? "&" : "") + newkey[i] + "=" + obj[newkey[i]];
        }
    }
    return str
}

export default service
